import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_tindercard/flutter_tindercard.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shishi/bean/randomshi.dart';
import 'package:shishi/bean/tangshibean.dart';
import 'package:shishi/page/SearchPage.dart';
import 'package:url_launcher/url_launcher.dart';
import '../Colors.dart';
import 'Drawer.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int random = Random().nextInt(15);
  int page = 1;
  int num = 10;
  List<shi> _listshi = new List<shi>();
  TangShi tangShi;
  Color _color = Colors.white;
  int _index = 0;


  void GetTangShi() async {
    try {
      Response response = await Dio().get(
          "http://api.tianapi.com/txapi/poetry/index?key=a69400da230d90d3d4ed644b6d3d1fb7&num=10&page=$page");
      tangShi = new TangShi(response.data);

      _listshi.addAll(tangShi.newslist);

      setState(() {});
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    GetTangShi();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onBackPressed,
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            '曦诗',
            style: TextStyle(
              fontFamily: 'lixuke',
            ),
          ),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.favorite,
                color: _color,
              ),
              onPressed: () {
                setState(() {
                  _color = Colors.red;
                });
              },
            ),
            IconButton(
              icon: Icon(
                Icons.search,
                color: Colors.white,
              ),
              onPressed: () {
                Navigator.of(context)
                    .push(CupertinoPageRoute(builder: (context) => Search()));
              },
            ),
            IconButton(onPressed: (){
              launch("https://www.bilibili.com/");
            }, icon: Icon(FontAwesomeIcons.chrome)),
            IconButton(
              tooltip: "分享",
                onPressed: (){
              Share.share('${_listshi[_index].content}');
            }, icon: Icon(Icons.share))
          ],
        ),
        body: body(),
        drawer: Drawer(
          child: DrawerPage(),
        ),
      ),
    );
  }

  Widget body() {
    if (_listshi.length > 0) {
      return  TinderSwapCard(
            orientation: AmassOrientation.TOP,
            totalNum: 200,
            stackNum: 4,
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height * 0.85,
            minWidth: MediaQuery.of(context).size.width * 0.8,
            minHeight: MediaQuery.of(context).size.height * 0.7,
            cardBuilder: (context, index) {
              return GestureDetector(
                  child: Card(
                    elevation: 10,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadiusDirectional.circular(10)),
                    clipBehavior: Clip.antiAlias,
                    child: SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(top: 15, left: 10, right: 10),
                            child: Text(
                              '${_listshi[index].title}',
                              style: TextStyle(
                                fontFamily: 'yuwei',
                                fontSize: 30,
                              ),
                            ),
                          ),
                          Text(
                            '${_listshi[index].author}',
                            style: TextStyle(
                                fontFamily: 'lixuke',
                                fontSize: 18,
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.all(18),
                            child: Text(
                              '${_listshi[index].content}',
                              style: TextStyle(fontSize: 20, fontFamily: 'kai'),
                            ),
                          ),
                          Container(
                              margin: EdgeInsets.all(10),
                              child: Text(
                                '${_listshi[index].intro}',
                              )),
                        ],
                      ),
                    ),
                  ),

                  onDoubleTap: () {
                    setState(() {
                      _color = Colors.red;
                    });
                  },
                );
            },
            swipeUpdateCallback: (DragUpdateDetails details, Alignment align) {},
            swipeCompleteCallback: (CardSwipeOrientation orientation, int index) {
              _index = index+1;
              if (index == _listshi.length - 4) {
                page++;
                GetTangShi();
              }
              setState(() {
                _color = Colors.white;
              });
            });
    } else {
      return SpinKitRipple(
        color: Cos.zhutise,
      );
    }
  }



  Future<bool> _onBackPressed() {
    return showDialog(
        context: context,
        builder: (context) =>
            CupertinoAlertDialog(
              title: Container(
                    child: Text(listshuiji[random]['shi'][0]+'\n'+listshuiji[random]['shi'][1],style: TextStyle(
                        fontFamily: 'yuwei',
                        fontSize: 30,
                        color: Cos.zhutise
                    ),),
                  ),

              content: Text('确定退出吗?'),

              actions: <Widget>[
                FlatButton(
                  child: Text('暂不'),
                  onPressed: () => Navigator.pop(context, false),
                ),
                FlatButton(
                  child: Text('确定'),
                  onPressed: () => Navigator.pop(context, true),
                ),
              ],
            ));
  }
  
}


